<template>
  <div>
    <div id="previewEditor" />
    <div v-if="type === 'judge'" class="saveBtn">
      <el-button
        type="primary"
        size="mini"
        @click="save"
      >保存
      </el-button>
      <el-button
        size="mini"
        @click="cancel"
      >关闭
      </el-button>
    </div>
  </div>
</template>

<script>
import Spreadsheet from '@hk/x-data-spreadsheet'
import { reportDetail, reportJudge } from '@/api/specialProject/safetyReportManagement'
import { exportExcel } from '@/utils/sheet'

export default {
  data() {
    return {
      id: this.$route.query.id,
      name: '',
      content: '[]',
      xs: null,
      type: this.$route.query.type,
      judgeXsOption: {
        showToolbar: true,
        showGrid: true,
        mode: 'edit'
      },
      previewXsOption: {
        showToolbar: false,
        showGrid: true,
        mode: 'read'
      }
    }
  },
  async mounted() {
    await this.getPreviewData()
    const exportEl = document.createElement('img')
    exportEl.src = ''
    exportEl.width = 16
    exportEl.height = 16
    this.judgeXsOption.extendToolbar = {
      left: [
        {
          tip: '导出',
          el: exportEl,
          onClick: (data, sheet) => {
            this.export2File()
          }
        }
      ]
    }
    this.$nextTick(() => {
      this.xs = new Spreadsheet('#previewEditor',
        this.type === 'judge' ? this.judgeXsOption : this.previewXsOption
      ).loadData(JSON.parse(this.content || '[]'))
      if (this.type === 'download') {
        this.download()
      }
    })
  },
  methods: {
    async getPreviewData() {
      await reportDetail(this.id).then((res) => {
        this.name = res.reportName
        this.content = res.content
      })
    },
    save() {
      reportJudge({ id: this.id, judgeContent: JSON.stringify(this.xs.getData()) }).then(() => {
        this.$message.success('保存成功')
      })
    },
    cancel() {
      window.close()
    },
    export2File() {
      exportExcel(this.xs, this.name || '模板')
    },
    download() {
      exportExcel(this.xs, this.name || '模板', () => window.close())
    }
  }
}
</script>

<style lang="scss" scoped>
.saveBtn {
  position: fixed;

  right: 10px;
  top: 5px;
}
</style>
